package multi_data.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * demoncat-a 数据库源
 * 
 * @author 延晓磊
 *
 * @since 2017年9月5日
 */
@Configuration
@MapperScan(basePackages = ADataSourceConfig.PACKAGE, sqlSessionFactoryRef = "aSqlSessionFactory")
public class ADataSourceConfig {

    // Mapper接口和配置使用不同的路径，从而隔离数据源，这样就直接在Dao层处理了多数据源的切换
    static final String PACKAGE = "cn.demoncat.a.mapper";
    static final String MAPPER_LOCATION = "classpath*:/mapper/a/*Mapper.xml";
 
    /**
     * 数据源
     * 
     * @author 延晓磊
     *
     * @since 2017年9月5日
     */
    // 刷新配置
    // @RefreshScope
    @Primary
    @Bean(name = "aDataSource")
	@ConfigurationProperties(prefix = "a.datasource")
    public DataSource aDataSource() {
    	return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }
    
    /**
     * 事物管理器
     * 
     * @author 延晓磊
     *
     * @since 2017年9月5日
     */
    @Primary
    @Bean(name = "aTransactionManager")
    public DataSourceTransactionManager aTransactionManager(@Qualifier("aDataSource") DataSource aDataSource) {
        return new DataSourceTransactionManager(aDataSource);
    }
    
    /**
     * sqlSessionFactory
     * 
     * @author 延晓磊
     *
     * @since 2017年9月5日
     */
    @Primary
    @Bean(name = "aSqlSessionFactory")
    public SqlSessionFactory aSqlSessionFactory(@Qualifier("aDataSource") DataSource aDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(aDataSource);
        //指定XML配置地址
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}